package com.zh.flowable.config.filter;

import com.zh.flowable.support.LoginUserHolder;
import com.zh.mycommon.util.MyCommonUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import java.io.IOException;
import java.util.Set;

/**
 * 用户认证过滤器
 *
 * @author
 * @date 2025/8/19
 */
@Component
public class AuthFilter extends OncePerRequestFilter {

    static Set<String> whiteList = Set.of("/login", "/api/auth/login");

    // 白名单直接放行;
    // 页面请求直接放行;
    // 接口请求需要校验token;
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        var uri = request.getRequestURI();
        return whiteList.contains(uri);
    }

    // 认证逻辑
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        var uri = request.getRequestURI();

        Cookie cookie1 = WebUtils.getCookie(request, "token");
        System.out.println("AuthFilter : cookie token ... " + cookie1);

        boolean isApiRequest = uri.startsWith("/api/");

        //获取token值
        String token = null;
        if (isApiRequest) {
            token = request.getHeader("token");
        } else {
            Cookie cookie = WebUtils.getCookie(request, "token");
            if (cookie != null) {
                token = cookie.getValue();
            }
        }

        // 校验token
        if (token == null || token.isEmpty()) {
            var loginUrl = request.getContextPath() + "/login";
            response.sendRedirect(loginUrl);
            return;
        }

        System.out.println("AuthFilter : validate token ... " + uri);

        if (!validTokenAndSetUserInfo(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("token解析失败");
            return;
        }

        System.out.println("AuthFilter : valid token. access ... " + uri);
        filterChain.doFilter(request, response);
    }

    boolean validTokenAndSetUserInfo(String token) {
        try {
            String plaintext = MyCommonUtil.base64Decode(token);
            String[] split = plaintext.split(";");
            if (split.length != 3) {
                return false;
            }
            LoginUserHolder.putUser(split[0], split[1], split[2]);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
}
